package bat.iog.hytool.Host;

import java.awt.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class FindHost extends Thread {
    private JTable table;
    private DefaultTableModel dtm;
    private String ipRegex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
    private String maskRegex = "^[1]*[0]*$";
    private java.util.List<String> data = new ArrayList<>();

    private FindHost() {
        init();
        start();
    }

    public void init() {
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize();
        int screenHeight = screenSize.height;
        int screenWidth = screenSize.width;
        JFrame jFrame = new JFrame();
        jFrame.setTitle("主机搜索");
        jFrame.setSize(800, 300);
        jFrame.setLocation(screenWidth / 4, screenHeight / 4);
        jFrame.setResizable(false);

        JPanel jPanel = new JPanel();
        JButton jButtonGet = new JButton("网络搜索");
        JButton jButtonSet = new JButton("设置参数");

        Object[] columnNames = {"网卡", "IP地址", "MAC地址", "修改IP地址", "子网掩码", "网关地址"};
        Object[][] rowData = {};
        dtm = new DefaultTableModel(rowData, columnNames);
        table = new JTable(dtm) {
            public boolean isCellEditable(int row, int column) {
                if (column == 3 || column == 4 || column == 5) {
                    return true;
                }
                return false;
            }
        };
        Border border = BorderFactory.createLineBorder(Color.BLACK);
        table.setPreferredScrollableViewportSize(new Dimension(720, 150));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionBackground(Color.lightGray);
        table.setSelectionForeground(Color.BLUE);
        table.setRowHeight(20);
        table.getTableHeader().setBorder(border);
        table.setBorder(border);

        for (int i = 0; i < 6; i++) {
            TableColumn tableColumn = table.getColumnModel().getColumn(i);
            // 设置列的宽度、首选宽度、最小宽度、最大宽度
            tableColumn.setWidth(120);
            tableColumn.setPreferredWidth(120);
            tableColumn.setMinWidth(120);
            tableColumn.setMaxWidth(120);
        }

        JScrollPane jScrollPane = new JScrollPane(table);

        jButtonGet.addActionListener(arg0 -> {
            data.clear();
            dtm.setRowCount(0);
            DatagramSocket dgSocket = null;
            try {
                dgSocket = new DatagramSocket();
                byte b[] = "gethostmessage".getBytes();
                DatagramPacket dgPacket = new DatagramPacket(b, b.length, InetAddress.getByName("255.255.255.255"), 8989);
                dgSocket.send(dgPacket);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                dgSocket.close();
            }
        });

        jButtonSet.addActionListener(arg0 -> {
            if (table.isEditing()) {
                table.getCellEditor().stopCellEditing();
            }
            DatagramSocket dgSocket = null;
            try {
                dgSocket = new DatagramSocket();

                for (int i = 0; i < dtm.getRowCount(); i++) {
                    String str3 = (String) dtm.getValueAt(i, 3);
                    if (str3 == null || str3.isEmpty()) {
                        continue;
                    } else if (!str3.matches(ipRegex)) {
                        dtm.setValueAt("IP地址不合法", i, 3);
                        return;
                    }

                    String str4 = (String) dtm.getValueAt(i, 4);
                    if (str4 == null || str4.isEmpty()) {
                        continue;
                    } else if (!str4.matches(ipRegex)) {
                        dtm.setValueAt("子网掩码不合法", i, 4);
                        return;
                    }
                    String[] masks = str4.split("\\.");
                    String binaryVal = "";
                    for (int j = 0; j < masks.length; j++) {
                        String binaryStr = Integer.toBinaryString(Integer.parseInt(masks[j]));
                        Integer times = 8 - binaryStr.length();
                        for (int k = 0; k < times; k++) {
                            binaryStr = "0" + binaryStr;
                        }
                        binaryVal += binaryStr;
                    }
                    if (!binaryVal.matches(maskRegex)) {
                        dtm.setValueAt("子网掩码不合法", i, 4);
                        return;
                    }

                    String str5 = (String) dtm.getValueAt(i, 5);
                    if (str5 == null || str5.isEmpty()) {
                        continue;
                    } else if (!str5.matches(ipRegex)) {
                        dtm.setValueAt("网关地址不合法", i, 5);
                        return;
                    }

                    StringBuffer stringBuffer = new StringBuffer("sethostmessage");
                    String str;
                    for (int j = 0; j < dtm.getColumnCount(); j++) {
                        str = (String) dtm.getValueAt(i, j);
                        stringBuffer.append(str);
                        stringBuffer.append(',');
                    }
                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    byte b[] = stringBuffer.toString().getBytes();
                    DatagramPacket dgPacket = new DatagramPacket(b, b.length, InetAddress.getByName("255.255.255.255"), 8989);
                    dgSocket.send(dgPacket);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                dgSocket.close();
            }
            jButtonGet.doClick();
        });

        Border hostBorder = BorderFactory.createTitledBorder("主机信息");
        jScrollPane.setBorder(BorderFactory.createCompoundBorder(hostBorder, BorderFactory.createEmptyBorder(10, 10, 10, 10)));

        jPanel.add(jScrollPane);
        jPanel.add(jButtonGet);
        jPanel.add(jButtonSet);

        jFrame.add(jPanel);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }

    public void run() {
        try {
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
            DatagramSocket socket = new DatagramSocket(8990);
            while (true) {
                socket.receive(packet);
                String message = new String(packet.getData()).substring(0, packet.getLength());
                if (!data.contains(message)) {
                    data.add(message);
                    String[] messageArr = message.split(",");
                    dtm.addRow(messageArr);
                }
                sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FindHost fh = new FindHost();
    }
}
